<script setup lang="tsx">
import { ModalUtil } from '/@lib/utils/modal.ts'
import { useModalStatus } from '/@lib/hooks/useModalStatus.ts'
import { useLoading } from '/@lib/hooks/useLoading.ts'
import { useForm } from '/@lib/hooks/useForm.ts'
import { MenuType, sys_normal_disable } from '/@/const/Options.ts'
import { MenuForm, MenuTypeEnum, MenuVO } from '/@/api/system/sysMenu/types.ts'
import { ApiSysMenu } from '/@/api/system/sysMenu'

const { loading, showLoading, hideLoading } = useLoading()
const { modalVisible, modalTitle, showModal, hideModal, setModalTitle } = useModalStatus()
const formRef = ref()
const { form, resetForm } = useForm<MenuForm>({
  path: '',
  menuId: undefined,
  parentId: 0,
  menuName: '',
  icon: '',
  menuType: MenuTypeEnum.Dir,
  sortNum: 1,
  isFrame: '1',
  isCache: '0',
  visible: '0',
  status: '0',
  levelHidden: '0',
  // hidden: '0',
  breadcrumbHidden: '0',
  noClosable: '0',
  dynamicNewTab: '0',
  isCustomSvg: '1',
  routerName: '',
  component: '',
  target: ''
})
const formRules = {
  menuName: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
  orderNum: [{ required: true, message: '顺序不能为空', trigger: 'blur' }],
  path: [{ required: true, message: '路由地址不能为空', trigger: 'blur' }],
  routerName: [{ required: true, message: '路由名称不能为空', trigger: 'blur' }],
  component: [{ required: true, message: '组件路径不能为空', trigger: 'blur' }],
  perms: [{ required: true, message: '权限标识不能为空', trigger: 'blur' }]
}
const closeCancel = () => {
  formRef.value?.resetFields()
  resetForm()
  hideModal()
}
// const opeRow = ref()
const menuOptions = ref<any[]>([])

/** 打开 Modal 操作 */
const openAdd = async (row: any, treeData: MenuVO[]) => {
  showModal()
  setModalTitle('添加菜单')
  if (row) {
    form.parentId = row.menuId
  }
  await handleOpenDefaultData(treeData)
}
const openEdit = async (row: any, treeData: MenuVO[]) => {
  showModal()
  setModalTitle('修改菜单')
  Object.assign(form, row)
  await handleOpenDefaultData(treeData)
}
defineExpose({ openAdd, openEdit })
const emit = defineEmits(['submit-success'])
/** 提交按钮 */
const submitForm = async () => {
  try {
    await formRef.value?.validate()
    showLoading()
    if (form.menuId) {
      await ApiSysMenu.update(form)
    } else {
      await ApiSysMenu.save(form)
    }
    ModalUtil.msgSuccess('操作成功')
    hideModal()
    emit('submit-success')
  } finally {
    hideLoading()
  }
}
/** Modal Open 处理默认数据 */
const handleOpenDefaultData = async (treeData: any) => {
  // opeRow.value = row
  const menu: any = { menuId: 0, menuName: '根类目', children: [] }
  menu.children = treeData
  menuOptions.value.push(menu)
}

const iconSelectorVisible = ref(false)
const handleIconSelector = () => {
  iconSelectorVisible.value = true
}
const handleIcon = (icon: string) => {
  form.icon = icon
  iconSelectorVisible.value = false
}

// const dirFlag = computed(() => form.menuType === 'M')
// const menuFlag = computed(() => form.menuType === 'C')
// const buttonFlag = computed(() => form.menuType === 'F')
const dirFlag = computed(() => form.menuType === '0')
const menuFlag = computed(() => form.menuType === '1')
const buttonFlag = computed(() => form.menuType === '2')

const formItems = ref([
  {
    prop: 'menuType',
    label: '菜单类型',
    span: 2,
    slot: 'agel-radio',
    attrs: {
      button: true,
      options: MenuType,
      onChange: (val: string) => {
        console.log('val', val)
        if (val === '2') {
          // 按钮
          formRef.value?.clearValidate('perms')
          formRef.value?.clearValidate('path')
        } else if (val === '1') {
          // 菜单
          // formRef.value?.clearValidate('path')
        } else {
        }
      }
    }
  },
  {
    prop: 'parentId',
    label: '上级菜单',
    span: 2,
    slot: 'slot-parentId',
    // hidden: true,
    attrs: {
      placeholder: '请输入上级菜单'
    }
  },
  {
    prop: 'menuName',
    // label: '菜单名称',
    label: computed(() => (buttonFlag.value ? '按钮名称' : '菜单名称')),
    attrs: {
      placeholder: '请输入名称'
    },
    rules: computed(() => formRules.menuName)
  },
  {
    prop: 'icon',
    label: '菜单图标',
    slot: 'slot-icon',
    hidden: computed(() => buttonFlag.value),
    attrs: {
      placeholder: '请输入菜单图标'
    }
  },
  {
    prop: 'perms',
    label: '权限标识',
    span: 2,
    hidden: computed(() => dirFlag.value),
    attrs: {
      placeholder: '请输入权限标识'
    },
    rules: computed(() => (!dirFlag.value ? formRules.perms : undefined))
  },
  {
    prop: 'sortNum',
    label: '显示排序',
    slot: 'el-input-number',
    attrs: {
      placeholder: '请输入显示排序',
      min: 0
    },
    rules: computed(() => formRules.orderNum)
  },

  {
    prop: 'path',
    // label: "路由地址",
    hidden: computed(() => buttonFlag.value),
    label: () => {
      return (
        <span>
          <el-tooltip
            content="访问的路由地址，如：`user`，
                如外网地址需内链访问则以`http(s)://`开头"
            placement="top"
          >
            <el-icon>
              <question-filled />
            </el-icon>
          </el-tooltip>
          路由地址
        </span>
      )
    },
    attrs: {
      placeholder: '请输入路由地址(一级路由以 /开头)'
    },
    rules: computed(() => (!buttonFlag.value ? formRules.path : undefined))
  },
  {
    prop: 'routerName',
    label: '路由名称',
    hidden: computed(() => buttonFlag.value),
    attrs: {
      placeholder: '请输入路由名称'
    },
    rules: computed(() => (!buttonFlag.value ? formRules.routerName : undefined))
  },
  {
    prop: 'component',
    label: '组件路径',
    hidden: computed(() => buttonFlag.value),
    slot: 'slot-component',
    // hidden: computed(() => dirFlag.value || buttonFlag.value),
    attrs: {
      placeholder: '请输入组件路径,一级路由填入Layout,其他按实际情况填写'
    },
    // slots: {
    //   prepend: () => menuFlag.value || '/@/view/',
    //   append: () => menuFlag.value || '.vue'
    // },
    rules: computed(() => (menuFlag.value ? formRules.component : undefined))
  },
  {
    prop: 'queryParam',
    label: '路由参数',
    hidden: computed(() => dirFlag.value || buttonFlag.value),
    attrs: {
      placeholder: '请输入路由参数'
    }
  },

  {
    prop: 'status',
    label: '菜单状态',
    slot: 'agel-radio',
    attrs: {
      border: true,
      options: sys_normal_disable
    }
  },

  {
    // prop: 'extra',
    label: '扩展',
    slot: 'slot-extra',
    hidden: computed(() => buttonFlag.value)
  }
])
</script>

<template>
  <!-- 添加或修改对话框 -->
  <el-dialog
    class="menuAddOrUpdate-dialog"
    :title="modalTitle"
    v-model="modalVisible"
    width="50%"
    top="5vh"
    @close="closeCancel"
    append-to-body
    destroy-on-close
    :close-on-click-modal="false"
  >
    <el-form ref="formRef" v-loading="loading" :model="form" label-width="180px" label-position="right">
      <AgelFormDesc :items="formItems" border :column="1">
        <template #slot-parentId>
          <el-tree-select
            v-model="form.parentId"
            :data="menuOptions"
            :props="{ value: 'menuId', label: 'menuName', children: 'children' }"
            value-key="menuId"
            placeholder="选择上级菜单"
            check-strictly
            default-expand-all
          />
        </template>
        <template #slot-icon>
          <div class="flex-align-center">
            <el-button @click="handleIconSelector" v-if="form.isCustomSvg !== '0'">
              <VipIcon :icon="form.icon" />
              <span>图标选择器</span>
              <VipIcon icon="arrow-down-s-line" />
            </el-button>
            <el-input v-model="form.icon" placeholder="请输入自定义SVG图标名称" v-else></el-input>
            <el-checkbox
              class="margin-left"
              v-model="form.isCustomSvg"
              label="自定义SVG图标"
              border
              true-value="0"
              false-value="1"
            />
          </div>
        </template>
        <template #slot-component>
          <el-input v-model="form.component" placeholder="请输入组件路径">
            <!-- <template #prepend v-if="menuFlag">/@/view/</template>
            <template #append v-if="menuFlag">.vue</template> -->
          </el-input>
        </template>
        <template #slot-extra>
          <el-form-item>
            <el-checkbox
              v-model="form.levelHidden"
              label="目录可显示"
              border
              true-value="0"
              false-value="1"
              v-if="dirFlag"
            />
            <el-checkbox
              v-model="form.visible"
              label="菜单可显示"
              border
              true-value="0"
              false-value="1"
              v-if="menuFlag"
            />
            <el-checkbox
              v-model="form.breadcrumbHidden"
              label="面包屑可显示"
              true-value="0"
              false-value="1"
              border
              v-if="!buttonFlag"
            />
            <el-checkbox v-model="form.isCache" label="可缓存" border true-value="0" false-value="1" v-if="menuFlag" />
            <el-checkbox
              v-model="form.noClosable"
              label="Tab标签页可关闭"
              true-value="0"
              false-value="1"
              border
              v-if="menuFlag"
            />
            <el-checkbox v-model="form.target" label="新窗口打开" true-value="_blank" false-value="" border v-if="menuFlag" />
            <el-checkbox v-model="form.isFrame" label="外链" true-value="0" false-value="1" border v-if="menuFlag" />
          </el-form-item>
        </template>
      </AgelFormDesc>
    </el-form>

    <!-- 底部按钮 -->
    <template #footer>
      <div class="flex-center width-full">
        <el-button @click="closeCancel">取消</el-button>
        <el-button :loading="loading" type="primary" @click="submitForm">提交</el-button>
      </div>
    </template>
  </el-dialog>
  <VipIconSelector v-model="iconSelectorVisible" @handle-icon="handleIcon"></VipIconSelector>
</template>

<style lang="scss">
.menuAddOrUpdate-dialog {
  max-height: 88vh !important;
  overflow: hidden;
  display: flex;
  flex-direction: column;

  .el-dialog__body {
    width: 100%;
    //height: 80%;
    flex: 1;
    display: flex;
    flex-flow: column;
    // overflow: hidden;
    overflow-y: auto;
    overflow-x: hidden;
  }
}
</style>

<style scoped lang="scss"></style>
